package mediatheque.alfresco.webscript;

import java.util.ArrayList;
import java.util.List;

import model.MediathequeModel;

import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.search.ResultSet;
import org.alfresco.service.cmr.search.SearchParameters;
import org.alfresco.service.namespace.QName;

public class WSListeMedias extends AbstractAlfrescoWebScript {

	private List<NodeRef> lstMedias = new ArrayList<NodeRef>();
	private QName typeMediaFilter;

	@Override
	protected void initFromRequest() throws Exception {
		String typeMedia = req.getParameter("type_media");

		// TODO : Traiter les différents types de médias ici !!!!
		if (typeMedia.equalsIgnoreCase("films")) {
			typeMediaFilter = MediathequeModel.TYPE_FILM;
		} else {
			// Cas par défaut : on pointe sur les films
			typeMediaFilter = MediathequeModel.TYPE_FILM;
		}
	}

	@Override
	protected void internalTraitement() throws Exception {
		lstMedias.clear();
		listMediasFromSelectedType();
		modele.put("listeMedias", lstMedias);
	}

	/**
	 * Récupération de la liste des médias chargés
	 */
	private void listMediasFromSelectedType() {
		String query = LuceneUtils.createQueryType("TYPE", typeMediaFilter);
		SearchParameters searchParam = LuceneUtils.baseCritere();
		searchParam.setQuery(query);
		ResultSet resultSet = searchService.query(searchParam);

		List<NodeRef> lstNoeuds = resultSet.getNodeRefs();
		if (lstNoeuds != null && !lstNoeuds.isEmpty()) {

			for (NodeRef currNode : lstNoeuds) {
				String ref = "/alfresco/d/d/";
				ref = ref.concat(currNode.toString());
				ref = ref.replaceAll("workspace:/", "workspace");
				ref = ref.concat("/file.bin");
				serviceRegistry.getNodeService().setProperty(currNode, MediathequeModel.PROP_URL_COVER, ref);
				System.out.println(ref);
			}
			lstMedias.addAll(lstNoeuds);
		}
	}
}
